﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GeoUtils;
using ListNetRanker;

namespace GeoCoderParser
{
    class ListNetGeoEntityChainRanker : IGeoEntityChainRanker
    {
        ListNetModule geoRanker;

        public ListNetGeoEntityChainRanker()
        {

        }

        public void Initialize(string strConfigFileName)
        {
            geoRanker = ListNetModule.CreateInstance(strConfigFileName);
        }

        public List<GeoEntityChain> RankGeoEntityChains(List<Token> tokenList, List<GeoEntityChain> geoEntityChainList, ViewPort viewport)
        {
            if (geoEntityChainList.Count <= 1)
            {
                //only one geo-entity chain, so no need to rank it
                return geoEntityChainList;
            }

            List<GeoEntityChain> rankedGeoChainsList = new List<GeoEntityChain>();
            List<ListNetRanker.IndexScore> rankedIndexScoreList = new List<ListNetRanker.IndexScore>();
            int pos = 0;
            foreach (GeoEntityChain item in geoEntityChainList)
            {
                //Feature extraction
                string strFeatureSet;
                strFeatureSet = GeocoderRankerFeatureGenerator.GeocoderRankerFeatureGenerator.Generate(tokenList, item, viewport);
                string strRecord = String.Format("{0} qid:1 {1}", pos, strFeatureSet);

                //Get geo-entity chain's ranking score
                Document doc = Document.Parse(strRecord);
                doc = geoRanker.GetNormalizer().normalize(doc);
                double score = geoRanker.GetRankScore(doc.features);

                rankedIndexScoreList.Add(new ListNetRanker.IndexScore(pos, score));
                pos++;
            }

            rankedIndexScoreList.Sort();
            foreach (ListNetRanker.IndexScore item in rankedIndexScoreList)
            {
                rankedGeoChainsList.Add(geoEntityChainList[item.index]);
            }

            return rankedGeoChainsList;

        }
    }
}
